#include "array_stack.h"
#include <stdlib.h>

ArrayStack* create(int capcity)
{
    ArrayStack* value=NULL;
    do
    {
        value=(ArrayStack*)malloc(sizeof(ArrayStack));
        if(!value)
        {
            printf("malloc stack data failed!\n");
            break;
        }

        value->data=(int*) malloc(capcity*sizeof(int));
        if(!value->data)
        {
            printf("malloc stack data failed!\n");
            
            free(value);
            value=NULL;
            break;
        }
        memset(value->data,0,capcity);
        value->size=0;
        value->capcity=capcity;
    } while (0);
    
    return value;
}


void destory(ArrayStack* stack)
{
    if(!stack)
    {
        return;
    }

    if(stack->data)
    {
        free(stack->data);
        stack->data=NULL;
    }

    free(stack);
    stack=NULL;
}

int push(ArrayStack* stack,int value)
{
    int result=kError;
    do
    {
        if(!stack)
        {
            printf("stack is invalid! NULL ptr!\n");
            break;
        }

        if(!stack->data || stack->capcity<stack->size)
        {
            printf("The stack is invalid!\n");
            break;
        }

        if(stack->size==stack->capcity)
        {
            printf("The stack is full\n");
            break;
        }

        stack->data[stack->size]=value;
        stack->size+=1;
        result=kSuccess;
    } while (0);
    return result;
}

int pop(ArrayStack* stack,int* value)
{
    int result=kError;
    do
    {
        if(!stack || !stack->data)
        {
            printf("stack is invalid!\n");
            break;
        }

        if(stack->size<1 || stack->capcity<1)
        {
            printf("The size of stack is too small!\n");
            break;
        }

        *value=stack->data[--stack->size];
        result=kSuccess;
    } while (0);
    return result;
}

int peek(ArrayStack* stack,int* value)
{
    int result=kError;
    do
    {
        if(!stack || !stack->data)
        {
            printf("stack is invalid!\n");
            break;
        }

        if(stack->size<1 || stack->capcity<1)
        {
            printf("The size of stack is too small!\n");
            break;
        }

        *value=stack->data[stack->size-1];
        result=kSuccess;
    } while (0);
    return result;
}